<?php

declare (strict_types=1);

namespace think\admin\service;

use think\admin\Exception;
use think\admin\Service;

/**
 * 多网关支持邮箱接口服务
 * Class EmailService
 * @package think\admin\service
 */
class EmailService extends Service
{
    /**
     * 验证邮箱验证码
     * @param string $email 邮箱
     * @param integer $wait 等待时间
     * @return array
     * @throws Exception
     */
    public function sendVerifyCode(string $email, int $wait = 120): array
    {
        $time = time();
        $sendTime = date('Y-m-d H:i:s', $time);  // 修正时间格式中的小时部分为大写 H
        $engine = sysconfig('SYS_BASE', 'SQM_SYS_DEFAULT_EMAIL_ENGINE');
        $emailFrom = sysconfig('EMAIL_LOCAL', 'SQM_EMAIL_LOCAL_FROM');
        $fromName = sysconfig('EMAIL_LOCAL', 'SQM_EMAIL_LOCAL_FROM_NICKNAME');

        // 检查是否已经发送
        $cacheKey = md5("code-{$engine}-{$email}");
        $cache = $this->app->cache->get($cacheKey, []);
        if (isset($cache['time']) && $cache['time'] + $wait > $time) {
            $remainingTime = $cache['time'] + $wait - $time;
            return [1, '验证码已经发送！', ['time' => $remainingTime]];
        }

        // 生成新的验证码
        $code = (string)rand(100000, 999999);
        $this->app->cache->set($cacheKey, ['code' => $code, 'time' => $time], 600);

        $subject = '用户邮箱验证码';
        $content = <<<EOF
<table cellpadding="0" cellspacing="0" border="0" width="700" class="main-wrap" style="margin:0 auto;color:#555;font:16px/26px '微软雅黑','宋体',Arail;background: #FBFBFB;width: 700px;    padding-bottom: 60px;">
    <tbody>
    <tr>
      <td style="padding: 30px 40px 20px 40px;border-bottom:1px solid #E8E9EB;margin-bottom:60px;">
        <div>亲爱的 用户：</div>
        <div>您的验证码为：</div>
        <div style="margin-top:20px;margin-bottom:20px;font-size:24px;font-weight:bold">$code</div>
        <div>请注意该验证码将在 5 分钟后过期，请尽快完成验证。</div>
        <div style="margin:20px 0;">DualEngine
          <br>
          <span style="border-bottom:1px dashed #ccc;">
                <span style="border-bottom: 1px dashed rgb(204, 204, 204); position: relative;" >$sendTime</span>
            </span>
        </div>
      </td>
    </tr>
    </tbody>
  </table>
EOF;

        // 根据邮件引擎发送邮件
        $emailService = match ($engine) {
            'TENCENT' => TencentEmailService::instance(),
            'ALIYUN' => AlibabaEmailService::instance(),
            default => LocalEmailService::instance(),
        };

        $state = $emailService->singleSendMail($email, $emailFrom, $fromName, $subject, $content);

        if ($state) {
            return [1, '验证码发送成功！', ['time' => $wait]];
        } else {
            $this->app->cache->delete($cacheKey);
            return [0, '验证码发送失败，请稍候再试！', ['time' => 0]];
        }
    }


    /**
     * 验证邮箱验证码
     * @param string $code 验证码
     * @param string $email 邮箱验证
     * @return boolean
     * @throws Exception
     */
    public function checkVerifyCode(string $code, string $email): bool
    {
        $engine = sysconfig('SYS_BASE', 'SQM_SYS_DEFAULT_EMAIL_ENGINE');
        $cacheKey = md5("code-{$engine}-{$email}");
        $cache = $this->app->cache->get($cacheKey, []);

        if (isset($cache['code']) && $cache['code'] === $code) {
            $this->app->cache->delete($cacheKey);
            return true;
        } else {
            return false;
        }
    }

}